import React, { useState, useEffect } from 'react';
import { Button, Table, Space, Image, Card, Input, Select, Form, Modal, message, Upload, DatePicker, InputNumber, Tag } from 'antd';
import { PlusOutlined, SearchOutlined, MinusCircleOutlined } from '@ant-design/icons';
import locale from 'antd/locale/zh_CN';
import { ConfigProvider } from 'antd';
import {
  TV_SERIES_STATUS,
  TV_SERIES_TYPE,
  type TvSeriesInfo,
  getTvSeriesInfoPage,
  addTvSeriesInfo,
  updateTvSeriesInfo,
  deleteTvSeriesInfo
} from '@/services/TvSeriesInfo';
import { uploadFile } from '@/services/FileService';
import styles from './index.less';
import { famousPersonId } from '@/services';
import type { UploadFile } from 'antd/es/upload/interface';
import dayjs from 'dayjs';

const { TextArea } = Input;

const DramaWorks: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<TvSeriesInfo[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | undefined>();
  const [posterFile, setPosterFile] = useState<UploadFile[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  // 加载数据
  const loadData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const response = await getTvSeriesInfoPage({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        keyword: values.keyword,
        status: values.status,
        type: values.type,
      });
      setData(response.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: response.totalCount,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);


  // 处理取消
  const handleCancel = () => {
    setModalVisible(false);
    setEditingId(undefined);
    form.resetFields();
    setPosterFile([]);
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      // 处理播放源信息，过滤掉空对象
      const playSourceInfo = values.playSourceInfo?.filter((source: any) =>
        source && (source.sourceName?.trim() || source.sourceUrl?.trim())
      ) || [];

      console.log(posterFile)
      const submitData = {
        ...values,
        famousPersonId,
        poster: posterFile.length > 0 ? posterFile[0]?.response?.uid || posterFile[0]?.uid : null,
        releaseDate: values.releaseDate ? values.releaseDate.format('YYYY-MM-DD') : null,
        genre: values.genre?.trim().replace(/[,，、;；]\s*/g, ',') || '',
        playSourceInfo,
      };

      if (editingId) {
        await updateTvSeriesInfo({ ...submitData, id: editingId });
        message.success('更新成功');
      } else {
        await addTvSeriesInfo(submitData);
        message.success('添加成功');
      }
      handleCancel();
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这部影视吗？删除后无法恢复。',
      okText: '确认',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await deleteTvSeriesInfo([id]);
          message.success('删除成功');
          loadData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理编辑
  const handleEdit = (record: TvSeriesInfo) => {
    setEditingId(record.id);
    const formValues = {
      title: record.title,
      genre: record.genre,
      numberOfEpisodes: record.numberOfEpisodes,
      director: record.director,
      description: record.description,
      status: record.status,
      type: record.type,
      playRole: record.playRole,
      language: record.language,
      playSourceInfo: record.playSourceInfo,
      releaseDate: dayjs(record.releaseDate).isValid() ? dayjs(record.releaseDate) : undefined,
    };

    form.setFieldsValue(formValues);

    if (record.poster) {
      setPosterFile([{
        uid: record.poster.toString(),
        name: 'poster',
        status: 'done',
        url: `/api/file/play/${record.poster}`,
      }]);
    }
    setModalVisible(true);
  };


  // 添加处理字符串分割的函数
  const splitString = (str?: string) => {
    if (!str) return [];
    return str
      .replace(/，/g, ',')  // 替换中文逗号
      .replace(/、/g, ',')  // 替换顿号
      .replace(/;/g, ',')   // 替换分号
      .replace(/；/g, ',')  // 替换中文分号
      .split(',')
      .map(item => item.trim())
      .filter(Boolean);  // 过滤空字符串
  };

  // 处理海报上传
  const handlePosterUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    try {
      const fileId = await uploadFile(file);
      onSuccess({
        uid: fileId.toString(),
        name: file.name,
        status: 'done',
        url: `/api/file/play/${fileId}`,
      });
    } catch (error) {
      onError(error);
    }
  };


  // 处理搜索
  const handleSearch = async () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    loadData(1, 20);
  };

  // 处理重置
  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadData(1, 20);
  };

  // 处理图片预览
  const handlePreview = async (file: UploadFile) => {
    const resp = file.response
    if (resp) {
      const fileId = resp.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    } else {
      const fileId = file.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    }
  };

  // 影视作品列表列定义
  const columns = [
    {
      title: '剧名',
      dataIndex: 'title',
      key: 'title',
      width: '15%',
      render: (text: string) => (
        <span style={{ color: '#1890ff', fontWeight: 500 }}>{text}</span>
      ),
    },
    {
      title: '海报',
      dataIndex: 'poster',
      key: 'poster',
      width: '10%',
      render: (poster: string) => (
        poster ? (
          <Image
            src={`/api/file/play/${poster}`}
            alt="海报"
            width={60}
            height={60}
            style={{ objectFit: 'cover', borderRadius: 4 }}
            preview={{
              mask: '预览',
              maskClassName: styles.previewMask,
            }}
          />
        ) : '-'
      ),
    },
    {
      title: '饰演角色',
      dataIndex: 'playRole',
      key: 'playRole',
      width: '15%',
      render: (playRole: string) => (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
          {splitString(playRole).map((item, index) => (
            <Tag key={index} color="blue">
              {item}
            </Tag>
          ))}
        </div>
      ),
    },
    {
      title: '导演',
      dataIndex: 'director',
      key: 'director',
      width: '10%',
    },
    {
      title: '集数',
      dataIndex: 'numberOfEpisodes',
      key: 'numberOfEpisodes',
      width: '8%',
    },
    {
      title: '影视类型',
      dataIndex: 'type',
      key: 'type',
      width: '15%',
      render: (type: string) => {
        const typeLabel = TV_SERIES_TYPE[type as keyof typeof TV_SERIES_TYPE]?.label || '未知';
        let color = 'default';
        if (typeLabel === '电影') {
          color = 'blue';
        } else if (typeLabel === '剧集') {
          color = 'green';
        }
        return (
          <Tag color={color}>
            {typeLabel}
          </Tag>
        )
      },
    },
    {
      title: '类型',
      dataIndex: 'genre',
      key: 'genre',
      width: '15%',
      render: (genre: string) => (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
          {splitString(genre).map((item, index) => (
            <Tag key={index} color="blue">
              {item}
            </Tag>
          ))}
        </div>
      ),
      ellipsis: true,
    },
    {
      title: '语言',
      dataIndex: 'language',
      key: 'language',
      width: '8%',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '8%',
      render: (status: string) => {
        const statusConfig = {
          'WAITING_PLAY': { color: 'orange', text: '待播' },
          'PLAYING': { color: 'green', text: '在播' },
          'FINISHED': { color: 'blue', text: '已完结' },
        };
        const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '播出时间',
      dataIndex: 'releaseDate',
      key: 'releaseDate',
      width: '12%',
    },
    {
      title: '简介',
      dataIndex: 'description',
      key: 'description',
      width: '25%',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: '10%',
      render: (_: any, record: TvSeriesInfo) => (
        <Space>
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDelete(record.id || 0)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 渲染搜索表单
  const renderSearchForm = () => (
    <div className={styles.toolbarContent}>
      <div className={styles.searchForm}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
        >
          <Form.Item name="keyword">
            <Input
              placeholder="影视名称/简介"
              prefix={<SearchOutlined />}
              allowClear
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item name="type">
            <Select
              placeholder="影视类型"
              style={{ width: 120 }}
              options={Object.values(TV_SERIES_TYPE)}
              defaultValue=""
            />
          </Form.Item>
          <Form.Item name="status">
            <Select
              placeholder="状态"
              style={{ width: 120 }}
              options={Object.values(TV_SERIES_STATUS)}
              defaultValue=""
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
          <Form.Item>
            <Space style={{ marginLeft: 20 }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={() => setModalVisible(true)}>
                添加影视
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>

    </div>
  );

  // 渲染表单模态框
  const renderModal = () => (
    <Modal
      title={editingId ? '编辑影视' : '添加影视'}
      open={modalVisible}
      onCancel={handleCancel}
      footer={null}
      width={800}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
      >
        <Form.Item
          name="title"
          label="剧名"
          rules={[{ required: true, message: '请输入剧名' }]}
        >
          <Input maxLength={100} />
        </Form.Item>

        <Form.Item
          name="type"
          label="影视类型"
          rules={[{ required: true, message: '请选择影视类型' }]}
        >
          <Select
            placeholder="请选择影视类型"
            options={Object.values(TV_SERIES_TYPE).filter(item => item.value)}
          />
        </Form.Item>

        <Form.Item
          name="playRole"
          label="饰演角色"
        >
          <Input placeholder="多个角色用逗号、顿号分隔（如：韩芸汐、雷初夏）" maxLength={50} />
        </Form.Item>

        <Form.Item
          name="genre"
          label="类型"
        >
          <Input placeholder="多个类型用逗号、顿号分隔（如：剧情、喜剧）" maxLength={50} />
        </Form.Item>

        <Form.Item
          name="releaseDate"
          label="首播日期"
        >
          <DatePicker style={{ width: '100%' }} locale={locale.DatePicker} />
        </Form.Item>

        <Form.Item
          name="numberOfEpisodes"
          label="总集数"
        >
          <InputNumber min={1} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="director"
          label="导演"
        >
          <Input maxLength={50} />
        </Form.Item>

        <Form.Item
          name="description"
          label="简介"
        >
          <TextArea rows={4} maxLength={500} showCount />
        </Form.Item>

        <Form.Item
          name="poster"
          label="海报"
        >
          <Upload
            listType="picture-card"
            fileList={posterFile}
            onChange={({ fileList }) => setPosterFile(fileList)}
            customRequest={handlePosterUpload}
            maxCount={1}
            onPreview={handlePreview}
          >
            {posterFile.length === 0 && '+ 上传海报'}
          </Upload>
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
        >
          <Select
            options={Object.values(TV_SERIES_STATUS).filter(item => item.value)}
            placeholder="请选择状态"
          />
        </Form.Item>

        <Form.Item
          name="language"
          label="语言"
        >
          <Input maxLength={20} placeholder="如：国语" />
        </Form.Item>

        <Form.Item label="播放源信息">
          <Form.List name="playSourceInfo">
            {(fields, { add, remove }) => (
              <div className={styles.sourceList}>
                {fields.map(({ key, name, ...restField }) => (
                  <div key={key} className={styles.sourceItem}>
                    <div className={styles.sourceContent}>
                      <Form.Item
                        {...restField}
                        name={[name, 'sourceName']}
                        style={{ marginBottom: 12 }}
                      >
                        <Input placeholder="播放源名称（如：爱奇艺）" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'sourceUrl']}
                        style={{ marginBottom: 0 }}
                      >
                        <Input.TextArea
                          placeholder="播放源地址"
                          autoSize={{ minRows: 1, maxRows: 3 }}
                        />
                      </Form.Item>
                    </div>
                    {fields.length > 0 && (
                      <Button
                        type="link"
                        className={styles.deleteButton}
                        onClick={() => remove(name)}
                        icon={<MinusCircleOutlined />}
                        danger
                      />
                    )}
                  </div>
                ))}
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                  className={styles.addButton}
                >
                  添加播放源
                </Button>
              </div>
            )}
          </Form.List>
        </Form.Item>

        <Form.Item className={styles.modalFooter}>
          <Space>
            <Button onClick={handleCancel}>取消</Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );

  // 添加分页器变化处理函数
  const handleTableChange = (newPagination: any) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize,
    }));
    loadData(newPagination.current, newPagination.pageSize);
  };

  return (
    <ConfigProvider locale={locale}>
      <div className={styles.container}>
        <Card title="影视作品管理">
          <div className={styles.toolbar}>
            {renderSearchForm()}
          </div>
          <Table
            columns={columns}
            dataSource={data}
            scroll={{ y: 'calc(100vh - 380px)', scrollToFirstRowOnChange: false }}
            rowKey="id"
            loading={loading}
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              pageSizeOptions: ['20', '50', '100'],  // 添加可选的每页条数
            }}
            onChange={handleTableChange}  // 添加 onChange 处理函数
          />
          {previewImage && (
            <Image
              style={{ display: 'none' }}
              preview={{
                visible: previewOpen,
                src: previewImage,
                onVisibleChange: (visible) => {
                  setPreviewOpen(visible);
                  if (!visible) {
                    setPreviewImage('');
                  }
                },
              }}
            />
          )}
          {renderModal()}
        </Card>
      </div>
    </ConfigProvider>
  );
};

export default DramaWorks; 